<template>
  <div class="config_container checkRoomOrser">
    <el-button size="mini" @click="handleOpen">
      <el-tooltip class="item" effect="dark" content="请选中左侧检查部门后再进行排序" placement="top-start">
        <i class="el-icon-sort">排序</i>
      </el-tooltip>
    </el-button>
    <el-dialog :visible.sync="dialogVisible" top="3%" width="70%" append-to-body :close-on-click-modal="true" :destroy-on-close="true" :before-close="handleClose" class="config_setting_dialog">
      <div slot="title" class="dialog-title">
        <el-row>
          <span class="dialog-title-text">机房排序</span>
          <span class="dialog-text">【请拖拽行进行排序】</span>
          <!-- <el-button type="primary" style="float:right" @click="111">编辑</el-button> -->
        </el-row>
      </div>
      <el-table highlight-current-row :data="tableData" border row-key="id" class="box-table draggable-table ky-table" style="width: 100%;" v-loading="loading">
        <el-table-column prop="checkRoomOrser" header-align="center" label="排序" width="70">
          <template slot-scope="scope">
            <input class="el-input__inner" :value="scope.row.checkRoomOrser" @focus="saveTemp(scope.row.checkRoomOrser)" @change="handleEnter($event, scope.row, $event.target.value)"/>
          </template>
        </el-table-column>
        <el-table-column class-name="canDrag" align="left" prop="checkRoom" width="130" label="机房名称" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column class-name="canDrag" align="left" prop="checkRoomState" label="机房状态" width="80">
          <template slot-scope="scope">
            <span :class="scope.row.checkRoomState==='关闭' ? 'fc_red':'fc_success'">
              {{scope.row.checkRoomState}}
            </span>
          </template>
        </el-table-column>
        <el-table-column class-name="canDrag" align="left" prop="virtualRoom" label="机房类型" show-overflow-tooltip>
          <template slot-scope="scope">
            {{getVirtualRoomItem(scope.row.virtualRoom)}}
          </template>
        </el-table-column>
        <el-table-column class-name="canDrag" align="left" prop="depArea" label="影像区域" width="80" show-overflow-tooltip></el-table-column>
        <el-table-column class-name="canDrag" prop="department" width="80" header-align="center" label="执行科室" show-overflow-tooltip></el-table-column>
        <el-table-column class-name="canDrag" align="left" prop="checkGroup" label="分组" show-overflow-tooltip width="80"></el-table-column>
        <el-table-column class-name="canDrag" prop="modalityAddress" header-align="center" min-width="100" label="检查地点" show-overflow-tooltip></el-table-column>
        <el-table-column class-name="canDrag" prop="examType" header-align="center" label="检查类型" show-overflow-tooltip></el-table-column>
        <el-table-column class-name="canDrag" align="left" prop="modality" label="设备名称" show-overflow-tooltip></el-table-column>
        <el-table-column class-name="canDrag" prop="modality" width="80" header-align="center" label="设备类型" show-overflow-tooltip></el-table-column>
        <el-table-column class-name="canDrag" prop="machineType" header-align="center" label="设备型号" show-overflow-tooltip width="80"></el-table-column>
        <el-table-column class-name="canDrag" prop="roomNo" header-align="center" label="房间号" show-overflow-tooltip width="80"></el-table-column>
        <el-table-column class-name="canDrag" prop="areaName" width="120" header-align="center" label="医院院区名称" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="areaNo" header-align="center" label="医院院区代码" show-overflow-tooltip width="80"></el-table-column> -->
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
        <el-button size="small" type="primary" @click="settingSend">保存</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import bus from '@/api/bus.js'
import tableStyle from '@/utils/tableStyle.js'
import Sortable from 'sortablejs'
// import draggable from 'vuedraggable'
import {
  getCheckroomPages,
  postSetDepOrders
} from '@/api/api.js'
export default {
  props: {
    configVisible: {
      type: Boolean,
      default: false
    },
    hospitalCode: {
      type: String,
      default: ''
    },
    checkRoomValue: {
      type: String,
      default: ''
    }
  },
  // components: {
  //   draggable
  // },
  computed: {
    dialogVisible: {
      get() {
        return this.configVisible
      },
      set(val) {
        this.$emit('update:configVisible', val)
      }
    }
  },
  watch: {
    dialogVisible: {
      handler(val) {
        if (val) {
          // this.getAppConfig()
        }
      },
      immediate: true
    },
    rowOrder(newOrder) {
      this.tableData = newOrder.map(index => this.tableData[index])
    }
  },
  data() {
    return {
      loading: true,
      isDragging: false, // 是否正在拖拽
      dragData: null, // 保存拖拽的行数据
      oldInterData: '',
      rowOrder: [],
      tableStyle: tableStyle,
      params: [],
      isDraggle: true,
      saveRoomSort: [],
      tableData: [],
      draggedIndex: -1,
      dropIndex: -1, // 目标行索引
      draggedItem: null,
      // isDragging: false,
      draggedColumn: {},
      tbody: '',
      setScrollOut: null
    }
  },
  mounted() {
    bus.$on('checkRoomTableInfo', (data) => {
      this.params = data
      this.params.pageNumber = 1
    })
    // console.error('table', this.tableData)
  },
  destroyed() {
    bus.$off('checkRoomTableInfo')
  },
  methods: {
    saveTemp(oldVal) {
      this.oldInterData = oldVal
    },
    handleEnter(event, row, newVal) {
      let insertInfo = JSON.parse(JSON.stringify(this.tableData[this.oldInterData]))
      this.tableData = this.tableData.filter(item => item.id != insertInfo.id)
      if (newVal > this.tableData.length) {
        this.tableData.push(insertInfo)
      } else {
        this.tableData.splice(newVal, 0, insertInfo)
      }
      this.updateIndex(this.tableData)
    },
    handleOpen() {
      if (!this.params.hospitalCode) {
        this.$message.warning('页面还未加载完毕请稍等')
        return // 结束函数的执行，不再执行后续代码
      } else if (this.params.dep == '') {
        this.$message.warning('请先点击左侧对应的检查部门')
        return // 结束函数的执行，不再执行后续代码
      }
      this.dialogVisible = true
      this.loading = true
      getCheckroomPages(this.params).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.tableData = res.content.list
          this.tableData = this.tableData.slice().sort((a, b) => a.checkRoomOrser - b.checkRoomOrser)
          const tbody = document.querySelector('.draggable-table .el-table__body-wrapper tbody')
          const that = this
          Sortable.create(tbody, {
            animation: 200,
            handle: '.canDrag',
            dragClass: 'dragClass', // 设置拖拽样式类名
            ghostClass: 'ghostClass', // 设置拖拽停靠样式类名
            chosenClass: 'chosenClass', // 设置选中样式类名
            onEnd({ newIndex, oldIndex }) {
              // 拖拽排序数据
              that.saveRoomSort = []
              that.tableData.splice(newIndex, 0, that.tableData.splice(oldIndex, 1)[0])
              const newArray = that.tableData.slice(0)
              that.tableData = [] // 必须有此步骤，不然拖拽后回弹
              that.$nextTick(function () {
                that.tableData = newArray // 重新赋值，用新数据来刷新视图
                this.updateIndex(that.tableData) // 更改列表中的序号，使序号1.2.3.4.....显示，不然就是行拖拽后乱序显示如:3.2.4.1...
              })
            },
            onUpdated({ newIndex, oldIndex }) {
              // 拖拽排序数据
              that.saveRoomSort = []
              that.tableData.splice(newIndex, 0, that.tableData.splice(oldIndex, 1)[0])
              const newArray = that.tableData.slice(0)
              that.tableData = [] // 必须有此步骤，不然拖拽后回弹
              that.$nextTick(function () {
                that.tableData = newArray // 重新赋值，用新数据来刷新视图
                this.updateIndex(that.tableData) // 更改列表中的序号，使序号1.2.3.4.....显示，不然就是行拖拽后乱序显示如:3.2.4.1...
              })
            }
          })
        }
      }).catch(() => {
        this.loading = false
      })
    },
    updateIndex() {
      this.tableData.forEach((item, index) => {
        item.checkRoomOrser = index
        this.saveRoomSort.push({ checkRoomOrser: item.checkRoomOrser, id: item.id })
      })
      this.setScrollOut = setTimeout(() => {
        const currentRow = document.querySelector('.current-row')
        if (currentRow) {
          currentRow.scrollIntoView({ behavior: 'smooth', block: 'center' })
        }
      }, 0)
    },
    handleClose() {
      this.dialogVisible = false
      this.setScrollOut && clearTimeout(this.setScrollOut)
    },
    getVirtualRoomItem() {
      this.$emit('getVirtualRoomName')
      return this.checkRoomValue
    },
    settingSend() {
      let roomParams = {
        hospitalCode: this.hospitalCode,
        list: this.saveRoomSort
      }
      postSetDepOrders(roomParams).then(res => {
        this.loading = false
        this.$emit('refresh')
        this.dialogVisible = false
        if (res && res.code === 10000) {
          this.$message.success(res.message || '批量设置机房排序成功')
          this.setScrollOut && clearTimeout(this.setScrollOut)
        }
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.draggableTableBody{
  max-height: calc(100vh - 270px);
  overflow-y: auto;
}
.listBox{
  height: 52px;
  border-bottom: 1px solid #e8e8e8;
}
.listBoxItem{
  /* padding: 0px 10px; */
  flex: 1;
  cursor: pointer;
  display: flex;
  flex-direction: row;
}
.checkRoomOrser /deep/ .el-dialog__body{
  height: 500px;
  overflow: hidden;
  overflow-y: scroll;
  overflow-x: scroll;
}
.headerBox{
  background-color: #00c0ef;
  color: #ffffff;
  padding: 0 5px;
}
.box-table td {
  padding: 10px 0px !important;
}
.dragged-row {
  background-color: #00c0ef; /* 被拖动行的背景颜色 */
  color: #ffffff;
}
/* // 拖拽 */
.dragClass {
  background-color: rgba(0, 188, 235, 0.5) !important;
  color: #0000a3 !important;
}
/* // 停靠 */
.ghostClass {
  background-color: rgba(0, 191, 243, 0.1) !important;
}
/* // 选择 */
.chosenClass:hover > td {
  background-color: rgba(0, 188, 235, 0.2) !important;
}
.config_setting_dialog{
  /deep/ .el-dialog__body{
    padding: 10px 20px;
    height: 500px;
    overflow: hidden;
    overflow-y: scroll;
    overflow-x: scroll;
  }
}
.dialog-title-text {
  font-size: 20px;
}
.dialog-text {
  color: red;
}
.el-input .el-input__inner {
  position: relative;
  max-width: 100%;
  padding: 4px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  transition: border-color 0.3s, background-color 0.3s;
}
.el-input .el-input__inner::placeholder {
  color: #c0c4cc;
}
.el-input .el-input__inner:focus {
  border-color: #409eff;
  outline: none;
}
</style>
